<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="usersParams.query"
            placeholder="请输入内容"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              @click="getUserList"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserdiolog = true"
            >添加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="usersList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStatuChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              content="编辑角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="删除角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页查询区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="usersParams.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="usersParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog
      title="提示"
      :visible.sync="addUserdiolog"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加用户表单 -->
      <el-form
        :model="addForm"
        status-icon
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户" prop="username">
          <el-input type="password" v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserdiolog = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户 -->
    <el-dialog
      title="提示"
      :visible.sync="editUserdiolog"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 添加用户表单 -->
      <el-form
        :model="editForm"
        status-icon
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户">
          <el-input
            type="password"
            v-model="editForm.username"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserdiolog = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="提示" :visible.sync="setRolediolog" width="50%" @close="setRoleClose">
      <div>
        <p>姓名：{{ userInfo.username }}</p>
        <p>角色：{{ userInfo.role_name}}</p>
        <p>
          分配角色：
          <el-select v-model="setRoleSelect" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolediolog = false">取 消</el-button>
        <el-button type="primary" @click="setRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (regEmail.test(value)) {
        return callback();
      }
      return callback(new Error("邮箱格式不正确"));
    };
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      return callback(new Error("手机号格式不正确"));
    };
    return {
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 6, max: 15, message: "用户名长度为6-15", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "密码长度为6-15", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 6, max: 15, message: "手机号长度为6-15", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
      editFormRules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 6, max: 15, message: "手机号长度为6-15", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editForm: {
        username: "",
        email: "",
        mobile: "",
      },
      usersParams: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      totalNum: 0,
      usersList: [],
      rolesList: [],
      addUserdiolog: false,
      editUserdiolog: false,
      setRolediolog: false,
      editForm: {},
      userInfo: {},
      setRoleSelect:'',
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.usersParams,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败！");
      }
      this.usersList = res.data.users;
      this.totalNum = res.data.total;
      console.log(res);
    },
    handleSizeChange(newSize) {
      this.usersParams.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.usersParams.pagenum = newPage;
      this.getUserList();
    },
    async userStatuChange(userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put(
        `/users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      console.log(res);
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("修改失败");
      }
      return this.$message.success("修改成功");
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请检查用户信息");

        const { data: res } = await this.$http.post("/users", this.addForm);

        if (res.meta.status !== 201) return this.$message.error("用户添加失败");

        this.$refs.addFormRef.resetFields();
        this.addUserdiolog = !this.addUserdiolog;
        this.getUserList();
      });
    },
    // 根据id获取用户信息
    async showEditUser(id) {
      this.editUserdiolog = true;
      const { data: res } = await this.$http.get(`/users/${id}`);
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("查询用户失败");
      this.editForm = res.data;
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;

        const { data: res } = await this.$http.put(
          "/users/" + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        );
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("更新失败");

        this.$message.success("更新成功");
        this.getUserList();
        this.editUserdiolog = !this.editUserdiolog;
      });
    },
    async removeUser(id) {
      const comfirmRes = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }
      ).catch((err) => err);
      if (comfirmRes !== "confirm") {
        return this.$message.info("已取消删除用户");
      }

      const { data: res } = await this.$http.delete("/users/" + id);

      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("用户删除失败");
      }

      this.$message.success("删除成功");
      this.getUserList();
    },
    async setRole(userInfo) {
      this.userInfo = userInfo;
      const { data: res } = await this.$http.get("roles");

      if (res.meta.status !== 200) return this.$message.error("获取角色错误");

      this.rolesList = res.data;
      console.log(res.data)
      this.setRolediolog = true;
    },
    async setRoleInfo(){
      if(!this.setRoleSelect) return this.$message.info('请选择需要分配的角色')
      const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{
        rid:this.setRoleSelect
      })
      if(res.meta.status !==200) return this.$message.error('更改失败')
      this.$message.success('更改成功')
      this.getUserList()
      this.setRolediolog = false
      
    },
    setRoleClose(){
      this.userInfo = {}
      this.setRoleSelect = ''
    }
  },
};
</script>

<style scoped>
</style>